package com.example.wearing.user;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wearing.R;
import com.example.wearing.tools.BitmapBinder;
import com.example.wearing.tools.ImageUtil;
import com.example.wearing.wardrobe.AddClothesActivity;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Map;

public class AddMatchActivity extends AppCompatActivity {

    private TextView timeContent, styleContent;
    private ImageView addImgBtn;

    private final static String TAG = "AddMatchActivity";
    private String matchTime, matchStyle;
    private int matchId;
    private String jdbcUser, jdbcUrl, jdbcPassword;
    private int userId;

    public static final int RESQUEST_CODE_CHOOSE = 2;
    private String imageBase64;
    private Bitmap imgBitmap;
    private String imageUrl = "";
    final String[] styles = {"休闲", "正式", "通勤", "甜美", "文艺", "复古"};

    private Handler handler;
    private Intent intent;
    private int intentFlag;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_match);
        init();
        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        //获取intent值
        intent = getIntent();
        intentFlag = intent.getIntExtra("m_flag", 0);
        if(intentFlag == 1){
            //说明为add
            Log.i(TAG, "onCreate: intent--add");
        }else if(intentFlag == 2){
            //说明为修改
            Log.i(TAG, "onCreate: intent--alter");
            matchTime = intent.getStringExtra("m_time");
            matchStyle = intent.getStringExtra("m_style");
            matchId = intent.getIntExtra("m_id", 0);
            //使用bundle接收
            Bundle bundle = intent.getExtras();
            BitmapBinder bitmapBinder = (BitmapBinder) bundle.getBinder("m_img");
            imgBitmap = bitmapBinder.getBitmap();
            imageBase64= ImageUtil.imageToBase64(imgBitmap);

            //将其放到控件中
            timeContent.setText(matchTime);
            styleContent.setText(matchStyle);
            addImgBtn.setImageBitmap(imgBitmap);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }

    public void init(){
        timeContent = findViewById(R.id.timeContent);
        styleContent = findViewById(R.id.styleContent);
        addImgBtn = findViewById(R.id.addImgBtn);

        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH)+1;
        matchTime = calendar.get(Calendar.YEAR)+"-"+month+"-"+calendar.get(Calendar.DAY_OF_MONTH);
        timeContent.setText(matchTime);

        matchStyle = styleContent.getText().toString().trim();

        //从SharedPreferences中获取数据
        SharedPreferences sp = this.getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        userId = sp.getInt("user_id",0);
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");
    }

    //点击添加照片，弹出相册
    public void chooseImage(View view){

        Log.i(TAG, "onClick: 相册");
        //从相册选取照片
        if(ContextCompat.checkSelfPermission(AddMatchActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            //真正去打开相册
            openAlbum();
        }else{
            //去申请权限
            ActivityCompat.requestPermissions(AddMatchActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }

    }

    //权限管理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 0) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                openAlbum();
            }else{
                Toast.makeText(this, "您没有获得访问相册权限~", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RESQUEST_CODE_CHOOSE){
            //从相册选取照片
            Uri uri = data.getData();
            String path = null;
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if(cursor != null) {
                if(cursor.moveToFirst()) {
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
                cursor.close();
            }
            if(path != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                imageUrl = path;
                Log.i(TAG, "onActivityResult: path:"+path);///storage/emulated/0/DCIM/Camera/IMG_20220301_180527.jpg

                addImgBtn.setImageBitmap(bitmap);
                imageBase64= ImageUtil.imageToBase64(bitmap);
            }
        }
    }

    private void openAlbum(){
        Intent intent = new Intent("android.intent.action.PICK");
        intent.setType("image/*");
        startActivityForResult(intent, RESQUEST_CODE_CHOOSE);
    }

    //选择日期
    public void selectMatchTime(View view) {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePicker = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                    {
                        Log.i(TAG, "onDateSet: 日期是："+year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日");
                        matchTime = year+"-"+(monthOfYear+1)+"-"+dayOfMonth;
                        timeContent.setText(matchTime);
                    }
                },calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePicker.show();
    }

    //选择风格
    public void selectMatchStyle(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择搭配风格");
        //    设置一个下拉的列表选择项
        builder.setItems(styles, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Log.i(TAG, "onClick: 选择的类别为：" + styles[which]);
                matchStyle = styles[which];
                styleContent.setText(matchStyle);
            }
        });
        builder.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    public void publishMatch(View view) {
        //设置种类、名称、颜色、图片不为空
        if(matchStyle.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择搭配风格", Toast.LENGTH_SHORT).show();
            return;
        }else if(matchTime.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择搭配时间", Toast.LENGTH_SHORT).show();
            return;
        }else if(imageBase64.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(getApplicationContext(), "正在提交，请稍等~", Toast.LENGTH_SHORT).show();

        //上传数据到表中
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){
                Log.i(TAG, "handleMessage: 收到消息");
                if(msg.what == 1){
                    //接收消息__add
                    int res = (int) msg.obj;
                    if(res == 1){
                        //发布成功
                        Toast.makeText(getApplicationContext(), "创建成功", Toast.LENGTH_SHORT).show();
                        //返回衣橱界面
                        setResult(20, intent);
                        finish();
                    }else if(res == 2){
                        //发布失败
                        Toast.makeText(getApplicationContext(), "创建失败", Toast.LENGTH_SHORT).show();
                    }
                }else if(msg.what == 2){
                    //接收消息————alter
                    int res = (int) msg.obj;
                    if(res == 1){
                        //修改成功
                        Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                        //返回衣橱界面
                        setResult(40, intent);
                        finish();
                    }else if(res == 2){
                        //发布失败
                        Toast.makeText(getApplicationContext(), "修改失败", Toast.LENGTH_SHORT).show();
                    }
                }
                super.handleMessage(msg);
            }
        };

        if(intentFlag == 1){
            Thread thread = new Thread(addMatchRun);
            thread.start();
        }else if(intentFlag == 2){
            Thread thread2 = new Thread(alterMatchRun);
            thread2.start();
        }

    }

    //添加衣物，insert数据库
    private Runnable addMatchRun = new Runnable() {
        @Override
        public void run() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
                Statement st = (Statement) cn.createStatement();
                int insertCode;
                try {
                    String insertSql = "INSERT INTO matches (m_time, m_style, m_img, m_uid) VALUES ('" + matchTime + "','" + matchStyle + "','" + imageBase64 + "'," + userId + ")";
                    int result = st.executeUpdate(insertSql);// 返回值代表收到影响的行数
                    Log.i(TAG, "run: 插入搭配数据成功" + result + "行");
                    insertCode = 1;

                } catch (SQLException e) {
                    insertCode = 2;
                    Log.i(TAG, "run:SQL fail!!!__" + e);
                    e.printStackTrace();
                }

                //发送消息
                Message msg = handler.obtainMessage(1, insertCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---插入结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };

    //修改衣物，update数据库
    private Runnable alterMatchRun = new Runnable() {
        @Override
        public void run() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser ,jdbcPassword);
                Statement st = (Statement) cn.createStatement();
                int updateCode;
                try {
                    String updateSql = "UPDATE matches set m_time = '" + matchTime+ "',m_style='"+ matchStyle
                            + "',m_img='" + imageBase64 + "' where m_id=" + matchId;
                    int result = st.executeUpdate(updateSql);// 返回值代表收到影响的行数
                    Log.i(TAG, "run: 修改match数据成功" + result + "行");
                    updateCode = 1;

                } catch (SQLException e) {
                    updateCode = 2;
                    Log.i(TAG, "run:SQL fail!!!__" + e);
                    e.printStackTrace();
                }

                //发送消息
                Message msg = handler.obtainMessage(2, updateCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---修改结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };
}